package com.qing.expert.modules.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qing.expert.common.exception.BusinessException;
import com.qing.expert.modules.admin.entity.Withdraw;
import com.qing.expert.modules.admin.mapper.WithdrawMapper;
import com.qing.expert.modules.admin.service.AdminFinanceService;
import com.qing.expert.modules.admin.vo.response.WithdrawVO;
import com.qing.expert.modules.user.entity.User;
import com.qing.expert.modules.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.time.LocalDateTime;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AdminFinanceServiceImpl implements AdminFinanceService {

    @Resource
    private WithdrawMapper withdrawMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public Page<WithdrawVO> getWithdrawList(Integer status, Integer page, Integer size) {
        // 构建查询条件
        LambdaQueryWrapper<Withdraw> wrapper = new LambdaQueryWrapper<>();
        if (status > 0) {
            wrapper.eq(Withdraw::getStatus, status);
        }
        wrapper.orderByDesc(Withdraw::getCreateTime);

        // 分页查询
        Page<Withdraw> withdrawPage = withdrawMapper.selectPage(new Page<>(page, size), wrapper);

        // 转换为VO对象
        Page<WithdrawVO> voPage = new Page<>(withdrawPage.getCurrent(), withdrawPage.getSize(),
                withdrawPage.getTotal());
        voPage.setRecords(withdrawPage.getRecords().stream().map(withdraw -> {
            WithdrawVO vo = new WithdrawVO();
            BeanUtils.copyProperties(withdraw, vo);

            // 查询用户信息
            User user = userMapper.selectById(withdraw.getUserId());
            if (user != null) {
                vo.setNickname(user.getNickname());
            }

            return vo;
        }).collect(Collectors.toList()));

        return voPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditWithdraw(String withdrawId, Integer action) {
        // 查询提现记录
        Withdraw withdraw = withdrawMapper.selectById(withdrawId);
        if (withdraw == null) {
            throw new BusinessException("提现记录不存在");
        }

        // 检查提现状态
        if (withdraw.getStatus() != 0) {
            throw new BusinessException("该提现申请已处理");
        }

        // 更新提现状态
        withdraw.setStatus(action);
        withdraw.setAuditTime(LocalDateTime.now());
        withdrawMapper.updateById(withdraw);

        // 如果拒绝提现，需要退回用户余额
        if (action == 2) {
            User user = userMapper.selectById(withdraw.getUserId());
            if (user != null) {
                user.setBalance(user.getBalance() + withdraw.getAmount().doubleValue());
                userMapper.updateById(user);
                log.info("退回用户[{}]提现金额[{}]", user.getUserId(), withdraw.getAmount());
            }
        }

        log.info("管理员审核提现申请[{}], 结果[{}]", withdrawId, action);
    }
}